package com.demo;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/AddToCartServlet")
public class AddToCartServlet  extends HttpServlet{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	
		 
		   String productIdArray[]=req.getParameterValues("productId");
		   HttpSession session=req.getSession();

		   Map<Integer, Integer> productIdCountMap=null;
 
		 productIdCountMap=(Map<Integer, Integer>) session.getAttribute("cartInfo");
		            
		   if(null==productIdCountMap){
			 productIdCountMap  =new  HashMap<Integer, Integer>();
		   }
		   
		   
		   
		    if(productIdArray.length>0){
		    	
 		    	for (String productId : productIdArray) {
                    
 		    		    int productIdInt=Integer.parseInt(productId);
 		    		    
 		    		    if(productIdCountMap.containsKey(productIdInt)){
 		    		    	 int counter=productIdCountMap.get(productIdInt);
 		    		    	 productIdCountMap.put(productIdInt, counter+1);
 		    		    }else {
 		    		    	productIdCountMap.put(productIdInt, 1);
 		    		    }
				}
 		
 		    	 session.setAttribute("statusMsg", "Product added successfully into cart");
 		    	  session.setAttribute("cartInfo", productIdCountMap);
 		    	 
		     }else {
		    
		    	 session.setAttribute("errorMsg", "Please select any product");
		    	 
		     }
		    
		    resp.sendRedirect("welcome.jsp");
		
	}
}
